#!/bin/bash
SERVICE_SCRIPT_DIR=$(basename $(dirname $0))
SERVICE_HOME=${MICROSERVICE_HOME}/${SERVICE_SCRIPT_DIR}
SERVICE_SCRIPT_HOME=${MICROSERVICE_SCRIPT_HOME}/${SERVICE_SCRIPT_DIR}
VIRTUALENV_HOME=$GLOBAL_VIRTUALENV_HOME
SERVICE_NAME=sysom-migration
ANCE_X86_PKG=ance-0.1.1-2.x86_64.rpm
ANCE_ARM_PKG=ance-0.1.1-2.aarch64.rpm
ANOLIS_X86_SQLITE=Anolis_OS-8.6.x86_64.sqlite
ANOLIS_ARM_SQLITE=Anolis_OS-8.6.aarch64.sqlite
ANOLIS_MIGRATION_PKGS_X86=anolis_migration_pkgs_x86_64.tar.gz
ANOLIS_MIGRATION_PKGS_ARM=anolis_migration_pkgs_aarch64.tar.gz

if [ "$UID" -ne 0 ]; then
    echo "Please run as root"
    exit 1
fi

install_requirement() {
    pushd ${SERVICE_SCRIPT_HOME}
    pip install -r requirements.txt
    popd
}

source_virtualenv() {
    echo "INFO: activate virtualenv..."
    source ${VIRTUALENV_HOME}/bin/activate || exit 1
}

check_or_download_ance() {
    mkdir -p ${SERVICE_HOME}/ance
    pushd ${SERVICE_HOME}/ance
    if [ ! -f "${ANCE_X86_PKG}" ]; then
        wget "https://ance.oss-cn-hangzhou.aliyuncs.com/release/x86_64/${ANCE_X86_PKG}"
    fi
    if [ ! -f "${ANCE_ARM_PKG}" ]; then
        wget "https://ance.oss-cn-hangzhou.aliyuncs.com/release/aarch64/${ANCE_ARM_PKG}"
    fi
    if [ ! -f "${ANOLIS_X86_SQLITE}" ]; then
        wget "https://ance.oss-cn-hangzhou.aliyuncs.com/databases/${ANOLIS_X86_SQLITE}"
    fi
    if [ ! -f "${ANOLIS_ARM_SQLITE}" ]; then
        wget "https://ance.oss-cn-hangzhou.aliyuncs.com/databases/${ANOLIS_ARM_SQLITE}"
    fi
    if [ ! -f "${ANOLIS_MIGRATION_PKGS_X86}" ]; then
        wget "https://gitee.com/src-anolis-sig/leapp/releases/download/v1.0.3-all-in-one/${ANOLIS_MIGRATION_PKGS_X86}"
    fi
    if [ ! -f "${ANOLIS_MIGRATION_PKGS_ARM}" ]; then
        wget "https://gitee.com/src-anolis-sig/leapp/releases/download/v1.0.3-all-in-one/${ANOLIS_MIGRATION_PKGS_ARM}"
    fi
    popd
}

install_app() {
    source_virtualenv
    install_requirement
    check_or_download_ance
}

install_app
